/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Menu, MenuItem } from '@blueprintjs/core';
import { Icon } from 'antd';

// Services
import { QueryService } from '../../../../services';

// Actions
import { actionCreators } from '../../../../actions';

// UI
import { BlockUi } from '../../../UI';

// Styles
import './WTExportMenu.css';

// Constants
const ICON_FONT_SIZE = '25px';
const ICON_COLOR = 'gray';
const ICON_THEME = 'filled';

class WTExportMenu extends Component {
  handleExportFile(fileType) {
    const {
      queryUuid,
      queryProperties,
      requestStart,
      requestSuccess,
      requestFailure
    } = this.props;
    const formatter = queryProperties['saiku.olap.result.formatter'];
    const fileExtension = fileType.toUpperCase();

    requestStart(<BlockUi message={`Exporting ${fileExtension} file...`} />);

    QueryService.exportFile(queryUuid, fileType, formatter)
      .then(res => requestSuccess())
      .catch(error => requestFailure());
  }

  render() {
    return (
      <Menu className="sku-export-menu">
        <MenuItem
          icon={
            <Icon
              type="file-pdf"
              style={{ fontSize: ICON_FONT_SIZE, color: ICON_COLOR }}
              theme={ICON_THEME}
            />
          }
          text="To PDF"
          onClick={this.handleExportFile.bind(this, 'pdf')}
        />
      </Menu>
    );
  }
}

WTExportMenu.propTypes = {
  queryUuid: PropTypes.string.isRequired,
  queryProperties: PropTypes.object.isRequired,
  requestStart: PropTypes.func.isRequired,
  requestSuccess: PropTypes.func.isRequired,
  requestFailure: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  queryUuid: state.query.query.name,
  queryProperties: state.query.query.properties
});

const mapDispatchToProps = dispatch => ({
  requestStart: message => dispatch(actionCreators.requestStart(message)),
  requestSuccess: () => dispatch(actionCreators.requestSuccess()),
  requestFailure: () => dispatch(actionCreators.requestFailure())
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(WTExportMenu);
